<?php
namespace app\job;

use think\facade\Queue;
use think\facade\Db;
use think\exception\ValidateException;
use think\queue\Job;

class UpdateFlexCourseUser
{

    public function fire(Job $job, array $data)
    {

        $isJobDone = $this->doUpdateFlexCourseUser($data);

        if ($isJobDone['code'] == 0) {

            $job->delete();

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassName = 'app\job\UpdateFlexCourseUser';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName = "UpdateFlexCourseUser";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $isJobDone['ts'], 'page' => $isJobDone['page'], 'timing_id' => $isJobDone['timing_id'], 'flex_id' => $isJobDone['flex_id']];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        } elseif($isJobDone['code'] == 1) {

            $job->delete();

            Db::name('timing')->where('id', '=', $data['timing_id'])->update(['state' => 2, 'complete_time'=>time()]);
        } else {
            if ($job->attempts() > 3){
                $job->delete();
            }

        }

    }


    /**
     * 根据消息中的数据进行实际的业务处理...
     * @param array $data
     * @return bool
     */
    protected function doUpdateFlexCourseUser(array $data)
    {

        $courseid = Db::name('flex_course')
            ->where('flex_id', '=', $data['flex_id'])
            ->column('courseid');

        if ($data['page'] == 1) {
            $res = Db::name('flex_course_user_'.$data['flex_id'])->find();
            if ($res) {
                Db::name('flex_course_user_'.$data['flex_id'])->delete(true);
            }
        }

        $user = Db::name('course_user')
            ->whereIn('courseid', $courseid)
            ->page($data['page'], 5000)
            ->select()
            ->toArray();

        if (!empty($user)) {

            $insert = [];

            foreach ($user as &$v) {
                $array = array(
                    'courseid' => $v['courseid'],
                    'rules_id' => $v['rules_id'],
                    'userid' => $v['userid'],
                    'type' => $v['type'],
                    'recommend_type' => $v['recommend_type'],
                    'add_time' => time()
                );
                array_push($insert, $array);
            }

            Db::name('flex_course_user_'.$data['flex_id'])->insertAll($insert);


            return ['code' => 0, 'ts' => $data['ts'], 'page' => ($data['page'] + 1), 'timing_id' => $data['timing_id'], 'flex_id' => $data['flex_id']];

        } else {
            return ['code' => 1];
        }
    }
}